package com.cuitrip.business.user;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.model.FormType;
import com.cuitrip.business.tripservice.model.SelectMenu;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.tripservice.ui.SelectMenuFragment;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.cuitrip.util.JumpSuccessUtil;
import com.cuitrip.util.MediaFetcher;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.jumper.FragmentJumper;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.imageupload.imp.QiniuService;
import com.lab.utils.imageupload.model.QiniuTokenObject;
import com.lab.widget.WordCountView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

/**
 * Created by sheena on 16/5/11.
 */
public class CompleteInsiderInfoFragment extends CustomUiFragment implements IProxyCallback {
    @Bind(R.id.v1)
    View mStep1;

    @Bind(R.id.v2)
    View mStep2;

    @Bind(R.id.v3)
    View mStep3;

    @Bind(R.id.civ_ava)
    CircleImageView mAvatar;

    @Bind(R.id.it_icon)
    IconTextView mCameraIcon;

    @Bind(R.id.tv_nickName)
    TextView mNickName;

    @Bind(R.id.il_address)
    ItemLayout mAddress;

    @Bind(R.id.il_gender)
    ItemLayout mGender;

    @Bind(R.id.wcv_self_intro)
    WordCountView mSelfIntroEdit;

    private ApiProxy mApiProxy=new ApiProxy(this);

    private static final int REQUEST_CODE_ID_SUCCESS=0X01;


    private ServiceInfo mServiceInfo;
    private CtUserInfo mUserInfo;
    private String headPicPara;
    private String genderPara;
    private String cityPara;
    private String introducePara;

    private static final String GENDER_MALE="1";
    private static final String GENDER_FEMALE="2";


    public static CompleteInsiderInfoFragment newInstance(ServiceInfo serviceInfo, CtUserInfo userInfo) {
        CompleteInsiderInfoFragment completeInsiderInfoFragment = new CompleteInsiderInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ServiceInfo.KEY, serviceInfo);
        bundle.putSerializable(CtUserInfo.KEY, userInfo);
        completeInsiderInfoFragment.setArguments(bundle);
        return completeInsiderInfoFragment;
    }

    private String[] genders = {ResourceUtil.getString(R.string.user_attribute_gender_value_male), ResourceUtil.getString(R.string.user_attribute_gender_value_female)};
    private File tempPhotoFile;
    private ImageFetcherManager mImageFetcherManager;
    private String mUploadedAvaUrl;
    private String cityChose;
    private String cityAbbr;
    private String country;
    private String countryName;
    private String address;

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.trip_operation_profile_title_1);
        config.mRightStyle= CustomUiConfig.AreaStyle.TEXT_STYLE;
        config.mTopbarRightAreaName=getString(R.string.operation_skip);
        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_create_trip_base_info);
        if (getArguments() != null) {
            mServiceInfo = (ServiceInfo) getArguments().getSerializable(ServiceInfo.KEY);
            mUserInfo = (CtUserInfo) getArguments().getSerializable(CtUserInfo.KEY);
        }
        return view;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        mSelfIntroEdit.getEditView().setTextSize(17);
    }

    @Override
    public void initData() {
        mImageFetcherManager = new ImageFetcherManager(this, ImageFetcherManager.Source.SELF_INFO_SELECT);
        if (mUserInfo != null) {
            headPicPara = mUserInfo.getHeadPic();
            genderPara = mUserInfo.getGender();
            cityChose = mUserInfo.getCity();
            introducePara = mUserInfo.getIntroduce();
            mSelfIntroEdit.setText(introducePara);
            StringBuilder builder=new StringBuilder();
            builder.append(getString(R.string.trip_operation_profile_name));
            builder.append(", ");
            builder.append(LoginInstance.getInstance().getUserInfo().getNick());
            mNickName.setText(builder);
            mUploadedAvaUrl = headPicPara;
            loadUserProfile();
            initProgress();
        }

    }

    @Override
    public void initListener() {

    }

    @OnClick(R.id.civ_ava)
    public void chooseAva() {
        tempPhotoFile = MediaFetcher.getTempImageFilePath(AppCoreRuntime.context);
        if (tempPhotoFile == null) {
            return;
        }
        EasyImage.openChooser(this, "", true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == ChooseCityActivity.REQUEST_CHOOSE_LOCATION) {
            cityChose = data.getStringExtra(ChooseCityActivity.CITY_NAME_KEY);
            cityAbbr = data.getStringExtra(ChooseCityActivity.CITY_ABBR_KEY);
            country = data.getStringExtra(ChooseCityActivity.COUNTRY_ABBR_KEY);
            countryName = data.getStringExtra(ChooseCityActivity.COUNTRY_NAME_KEY);
            address = data.getStringExtra(ChooseCityActivity.ADDRESS_KEY);
            loadUserProfile();
            return;
        }

        if (requestCode==REQUEST_CODE_ID_SUCCESS && resultCode==Activity.RESULT_OK){
            getHostActivity().finish();
        }
        boolean handleActivity = EasyImage.handleActivityResult(requestCode, resultCode, data, getHostActivity(), new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                boolean pickImageSuccess = mImageFetcherManager.cropImage(imageFile, tempPhotoFile, null);
                if (!pickImageSuccess) {
                    MessageUtils.showToast(R.string.feedback_data_err);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
        if (!handleActivity) {
            if (ImageFetcherManager.REQUEST_CODE_CROP_IMAGE == requestCode) {
                if (resultCode == Activity.RESULT_OK) {
                    Bitmap bp = GetImageHelper.getResizedBitmap(getHostActivity(), Uri.fromFile(tempPhotoFile));
                    if (bp != null) {
                        mAvatar.setImageBitmap(bp);
                        updateImage();
                    }
                }
            }
        }

    }

    protected void updateImage() {
        showLoading();
        QiniuService.INSTANCE.requestTokenObject(new QiniuService.RequestQiniuTokenCallback() {
            @Override
            public void onSuccess(QiniuTokenObject qiniuTokenObject) {
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                QiniuService.INSTANCE.asyncPutImage(QiniuService.INSTANCE.getObjectName(userInfo.getUid()), tempPhotoFile.getAbsolutePath(), new QiniuService.UploadCallback() {
                    @Override
                    public void onFailure(String errorMessage) {
                        hideLoading();
                        ToastUtil.toast(errorMessage);
                    }

                    @Override
                    public void onSuccess(String url) {
                        hideLoading();
                        mUploadedAvaUrl = url;
                    }

                    @Override
                    public void onProgress(int progress) {
                        AppLog.d("progress" + progress);
                    }
                });
            }

            @Override
            public void onFailed(String errorMessage) {
                hideLoading();
            }
        });
    }

    private void loadUserProfile() {
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo == null) {
            return;
        }
        if (mUploadedAvaUrl != null) {
            ImageHelper.displayImage(mUploadedAvaUrl, mAvatar, null);
            mCameraIcon.setVisibility(View.GONE);
        }

        if (cityChose!=null){
            mAddress.setleftText(cityChose);
        }

        if (genderPara!=null){
            if (GENDER_MALE.equals(genderPara)){
                mGender.setleftText(getString(R.string.user_attribute_gender_value_male));
            }else{
                mGender.setleftText(getString(R.string.user_attribute_gender_value_female));
            }
        }

        if (TextUtils.isEmpty(cityChose)) {
            mAddress.setleftText(getString(R.string.user_attribute_city_desc));
        } else {
            if (TextUtils.isEmpty(countryName) || countryName.equals(cityChose)) {
                mAddress.setleftText(cityChose);
            } else {
                mAddress.setleftText(countryName + "-" + cityChose);
            }

        }


    }

    @OnClick(R.id.il_address)
    public void chooseCity() {
        TrackUtil.trackScreenName("/user/about/edit/set/city");
        ChooseCityActivity.chooseLocation(this, ChooseCityActivity.PROFILE_MODE, false);
    }

    @OnClick(R.id.il_gender)
    public void chooseGender() {
        SelectMenuFragment selectMenuFragment = new SelectMenuFragment();
        final List<SelectMenu> selectMenuList = new ArrayList<>();
        for (int i = 0; i < genders.length; i++) {
            SelectMenu selectMenu = new SelectMenu();
            selectMenu.key = String.valueOf(i);
            selectMenu.value = genders[i];
            selectMenuList.add(selectMenu);
        }
        selectMenuFragment.setTitle(ResourceUtil.getString(R.string.user_attribute_gender));
        selectMenuFragment.setSelectMenuList(selectMenuList);
        showDialogFragment(selectMenuFragment);
        selectMenuFragment.setResultListener(new SelectMenuFragment.OnDataSelectBackListener() {

            @Override
            public void onSelect(SelectMenu selectMenu) {
                int i = Integer.parseInt(selectMenu.key);
                mGender.setleftText(selectMenuList.get(i).value);
                genderPara=selectMenuList.get(i).value;
            }
        });
    }

    @OnClick(R.id.tv_btn_next)
    public void next() {
        if (isAllComplete()) {
            showLoading();
            Map<String, String> map = new HashMap<>();
            if (mUploadedAvaUrl!=null){
                map.put("headPic", mUploadedAvaUrl);
            }
            if (getString(R.string.user_attribute_gender_value_male).equals(genderPara) || GENDER_MALE.equals(genderPara)){
                map.put("gender",GENDER_MALE);
            }else{
                map.put("gender",GENDER_FEMALE);
            }
            if (!TextUtils.isEmpty(address)) {
                map.put("city", address);
            }
            if(!TextUtils.isEmpty(cityAbbr)){
                map.put("cityAbbr",cityAbbr);
            }
            if (!TextUtils.isEmpty(country)){
                map.put("country",country);
            }
            if (!TextUtils.isEmpty(mSelfIntroEdit.getContent())){
                String introduce = mSelfIntroEdit.getContent().toString();
                map.put("introduce",introduce);
            }
            UserBusiness.updateProfile(mApiProxy, map);
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()){
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.MODIFY_USERINFO.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                if (response.result instanceof CtUserInfo) {
                    CtUserInfo ctUserInfo = (CtUserInfo) response.result;
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(ctUserInfo.getUid(), ctUserInfo.getNick(), Uri.parse(ctUserInfo.getHeadPic())));
                    hideLoading();
                    int validType = ctUserInfo.getValidType();
                    judgeJumper2WhichPage(validType);
                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    hideLoading();
                    MessageUtils.showToast(response.msg);
                }
            }
        }else if (ApiManager.SERVICE_COMMIT.equals(response.getApiName())) {
            hideLoading();
            if (response.isResponseNormal()) {
                if (response.result instanceof ServiceInfo) {
                    ServiceInfo serviceInfo = (ServiceInfo) response.result;
                    mServiceInfo.setSid(serviceInfo.getSid());
                    LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(
                            new Intent(TripServiceListFragment.TRIP_SERVICE_STATUS_CHANGED));
                    IndexActivity.gotoTab(getActivity(), IndexActivity.SERVICE_TAB_INDEX);
                    getActivity().finish();
                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }
        }

        return false;
    }

    private void initProgress(){
        mStep1.setBackgroundColor(ResourceUtil.getThemeColor());
        if ((mUserInfo.getValidType() & CtUserInfo.VALIDATE_MASK_PHONE)==CtUserInfo.VALIDATE_MASK_PHONE ) {
            mStep2.setBackgroundColor(ResourceUtil.getThemeColor());
        }else{
            mStep2.setBackgroundColor(ResourceUtil.getColor(R.color.ganshi_ded8d7));
        }
        if (CtUserInfo.ID_CHECK_FAILED==mUserInfo.getIdCheckStatus()||CtUserInfo.ID_CHECK_NONE==mUserInfo.getIdCheckStatus()){
            mStep3.setBackgroundColor(ResourceUtil.getColor(R.color.ganshi_ded8d7));
        }else{
            mStep3.setBackgroundColor(ResourceUtil.getThemeColor());
        }
    }

    private void judgeJumper2WhichPage(int validType){
        CtUserInfo ctUserInfo = LoginInstance.getInstance().getUserInfo();
        if ((validType & CtUserInfo.VALIDATE_MASK_PHONE)!=CtUserInfo.VALIDATE_MASK_PHONE ) {
            //手机未验证,跳转手机验证页面
            FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(),R.id.container,VerifyUserMoblieFragment.newInstance(mServiceInfo, mUserInfo),VerifyUserMoblieFragment.class.getName(),false);
        } else if (CtUserInfo.ID_CHECK_FAILED==ctUserInfo.getIdCheckStatus()||CtUserInfo.ID_CHECK_NONE==ctUserInfo.getIdCheckStatus()/*CtUserInfo.VALIDATE_MASK_IDCARD != validType && CtUserInfo.VALIDATE_MASK_INTERNATION_CARD != validType*/) {
            //身份Id未验证，跳转ID验证页面
            FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(),R.id.container,VerifyIDFragment.newInstance(mServiceInfo, mUserInfo),VerifyIDFragment.class.getName(),false);
        }else{
            //全部验证，跳转成功页
            mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
            ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
            JumpSuccessUtil.navigate2CreateTripSucPage(this,REQUEST_CODE_ID_SUCCESS);
        }
    }


    private boolean isAllComplete() {
        if (TextUtils.isEmpty(mUploadedAvaUrl)) {
            ToastUtil.toast(getHostActivity(), getString(R.string.user_complete_profile_picture_desc), 0);
            return false;
        }

        if (TextUtils.isEmpty(cityChose)) {
            ToastUtil.toast(getHostActivity(), getString(R.string.trip_operation_profile_notice_1), 0);
            return false;
        }

        if (TextUtils.isEmpty(genderPara)) {
            ToastUtil.toast(getHostActivity(), getString(R.string.trip_operation_profile_notice_2), 0);
            return false;
        }

        if (TextUtils.isEmpty(mSelfIntroEdit.getContent())) {
            ToastUtil.toast(getHostActivity(), getString(R.string.trip_operation_profile_notice_3), 0);
            return false;
        }

        return true;
    }

    @Override
    public void onTopbarRightPress() {
        if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft() || mServiceInfo.isChecking()) {
            if (ServiceFormProxy.getInstance().isFormComplete(mServiceInfo, FormType.TITLE)) {
                showLoading();
                mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
                ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
            }
        }

    }

    @Override
    public boolean onBackPressed() {
        return false;
    }


}
